package com.scy.jdbc;

import java.sql.*;

//使用JDBC操作数据库，实现新增
public class JDBCAdd {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("1");
            //获取数据库连接对象Connection
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/mydb",
                    "root",
                    "root"
            );
            System.out.println("2");
            //定义sql
            String sql = "insert into account value(?,?,?)";
            //创建传输器执行sql对象
            ps = conn.prepareStatement(sql);
            //设置占位符的值
            ps.setObject(1,null);
            ps.setString(2,"许涛涛");
            ps.setDouble(3,10000000);
            //获取执行sql语句的对象Statement（不能防止sql注入）
            //rows > 0表示新增成功反之失败
            int rows = ps.executeUpdate();
            //处理结果集
            if (rows > 0){
                System.out.println("新增成功，影响了"+rows+"行记录");
            }else {
                System.out.println("新增失败");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (ps!=null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
